<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ include file="/common/common.jsp" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>修改商品</title>
	<link href="${ctx}/static/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
    <link href="${ctx}/static/css/basic.css" rel="stylesheet" type="text/css">
    <link href="${ctx}/static/plugins/layer/skin/default/layer.css" rel="stylesheet" type="text/css"/>
    <link href="${ctx}/static/plugins/validationEngine/css/validationEngine.jquery.css" rel="stylesheet" type="text/css">
	<link href="${ctx}/static/dist/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
	<link href="${ctx}/static/plugins/zyupload/skins/zyupload-1.0.0.css" rel="stylesheet"  type="text/css"/>
	<link href="${ctx}/static/plugins/kindeditor-4.1.7/themes/default/default.css" rel="stylesheet"   type="text/css"/>
     <style type="text/css">
          .red{color: red;}
        .head_title_margin{  margin: 40px;  }
        .head_title{color: #00afd6;font-size: 24px}
        .fa-2 {
            font-size: 2em;
        }
        #addInput i:hover{
            color: blue;
        }
 		select{
        	width: 200px;
        	line-height: 33px;
        	height: 33px;
        }
    </style>
</head>
<body>
<div class="content text-center"  >
    <form class="form-horizontal" id="updateForm">
        <div class="head_title_margin"><span class="head_title"><strong>基本信息</strong></span><hr></div>
        <div class="form-group">
            <label for="" class="col-sm-1 control-label"><span class="red">*</span>供应商:</label>
            <div class="col-sm-3">
                <select  id="supplierId" name="supplierId"  class="form-control">
                	<c:forEach var="item" varStatus="status" items="${supplierList}">
                    	<option value="${item.id }" <c:if test="${item.id == phProductVo.supplierId}"> selected="selected"</c:if>>${item.supplierName}</option>
                    </c:forEach>
                </select>
            </div>
            <label for="" class="col-sm-1 control-label"><span class="red">*</span>商品名称:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control validate[required]"  name="productName" id="productName" value="${phProductVo.productName}"
                       placeholder="请输入商品名称" />
            </div>
            <label for="" class="col-sm-1 control-label">商品条形码:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control"  name="barCode" id="barCode" value="${phProductVo.barCode}"
                       placeholder="商品条形码可以为空" />
            </div>
        </div>

        <div class="form-group">
            <label for="" class="col-sm-1 control-label"><span class="red">*</span>商品数量:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control validate[required, custom[integer], min[1]]"  name="productCount" id="productCount" value="${phProductVo.productCount}"
                       placeholder="请输入商品数量" />
            </div>
            <label for="" class="col-sm-1 control-label">市场参考价:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control validate[custom[number], min[0]]"  name="referencePrice" id="referencePrice" value="${phProductVo.referencePrice}"
                       placeholder="市场参考价可以为空" />
            </div>
            <label for="" class="col-sm-1 control-label"><span class="red">*</span>零售价:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control validate[required,custom[number], min[0]]" onblur="setPurchasePrice()"  name="retailPrice" id="retailPrice" value="${phProductVo.retailPrice}"
                       placeholder="请输入零售价" />
            </div>
        </div>

        <div class="form-group">
            <label for="" class="col-sm-1 control-label"><span class="red">*</span>进货价:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control " readonly="readonly"  name="purchasePrice" id="purchasePrice" value="${phProductVo.purchasePrice}"/>
            </div>
            <label for="" class="col-sm-1 control-label"><span class="red">*</span>结算价:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control validate[required,custom[number], min[0]]"  name="settlementPrice" id="settlementPrice" value="${phProductVo.settlementPrice}"
                       placeholder="请输入结算价" />
            </div>
            <label for="" class="col-sm-1 control-label"><span class="red">*</span>市级起批数量:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control validate[required, custom[integer], min[1]]"  name="municipalBatchQuantity" id="municipalBatchQuantity" value="${phProductVo.municipalBatchQuantity}"
                       placeholder="请输入市级起批数量" />
            </div>
        </div>

        <div class="form-group">
            <label for="" class="col-sm-1 control-label"><span class="red">*</span>商户起批数量:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control validate[required, custom[integer], min[1]]" name="sellerbAtchQuantity" id="sellerbAtchQuantity" value="${phProductVo.sellerbAtchQuantity}"
                       placeholder="请输入商户起批数量" />
            </div>
            <label for="" class="col-sm-1 control-label">起售数量:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control validate[custom[integer], min[1]]"  name="saleQuantity" id="saleQuantity" value="${phProductVo.saleQuantity}"
                       placeholder="起售数量可以为空" />
            </div>
            <label for="" class="col-sm-1 control-label">物流费用:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control validate[custom[number], min[0]]"  name="freight" id="freight" value="${phProductVo.freight}"
                       placeholder="物流费用可以为空" />
            </div>
        </div>
         <div class="form-group">
            <label for="" class="col-sm-1 control-label">包邮数量:</label>
            <div class="col-sm-3">
                <input type="text" class="form-control validate[custom[number], min[0]]"      name="numberOfPackages" id="numberOfPackages" value="${phProductVo.numberOfPackages}"
                       placeholder="包邮数量可以为空" />
            </div>
        </div>
        <div class="head_title_margin"><span class="head_title"><strong>详细描述</strong></span><hr></h1></div>
        <div>
            <div class="form-group">
                <label for="" class="col-sm-1 control-label">详细描述:</label>
                <!-- 需要使用富文本 -->
                <div class="col-sm-11">
                <textarea class="form-control" name="description" rows="6" cols="276" id="description" >${phProductVo.description}</textarea>
                </div>
            </div>
        </div>
        <!-- -------------------------------------- 商品相册 -------------------------------------- -->
        <div class="head_title_margin"><span class="head_title"><strong>商品相册</strong></span><hr></div>
        <div class="form-group">
            <label class="col-sm-1 control-label">商品相册：</label>
            <div style="display: block;" id="existImage">
           	 <c:forEach var="img" varStatus="status" items="${phProductVo.phProductImageVoList}">
           	 	<div style="display: block;float: left;width: 250px; height: 150px;" class="existImageBox">
	           	 	<img src="${img.url}" width="200" height="100">
	           	 	<span onclick="deleteDiv(this)" class="fa fa-minus"></span>
			    	<input type="hidden" name="image" id="imgs${img.id}" class="hImag" value="${img.url}"/>
		    	</div>
			</c:forEach>
            </div>
        </div>
        <div class="form-group"><!-- 新上传 -->
            	<p>请上传商品的照片，照片大小不能超过5M，图片总数不能超过5张。</p>
            	<div id="zyupload" class="zyupload"></div> 
        </div>
         <!-- -------------------------------------- //商品相册 -------------------------------------- -->
        
        <div class="head_title_margin"><span class="head_title"><strong>商品属性值</strong></span><hr></div>
        <div class="form-group">
			<label for="" class="col-sm-1 control-label"><span style="color: red">*</span>商品分类:</label>
            <div class="col-sm-3">
                <select id="first" onchange="getClass(this.options[this.selectedIndex].value,'second');">
                	<option value="-1" selected="selected">请选择分类</option>
                	<c:forEach var="item" varStatus="status" items="${pcL1List}">
                   		<option value="${item.id }" <c:if test="${item.id == pcvP1.id}"> selected="selected"</c:if>>${item.classifyName}</option>
                    </c:forEach>
                </select>
            </div>
            <div class="col-sm-3">
                <select id="second" onchange="getClass(this.options[this.selectedIndex].value,'three');" >
               	 <option value="-1" selected="selected">请选择分类</option>
               	 <c:forEach var="item" varStatus="status" items="${pcL2List}">
                   	 <option value="${item.id }" <c:if test="${item.id == pcvParent.id}"> selected="selected"</c:if>>${item.classifyName}</option>
                    </c:forEach>
                </select>
            </div>
            <div class="col-sm-3">
                <select id="three" name="productClassifyId" onchange="gerProperties()" clas="validate[required,custom[number], min[1]]">
               	 <option value="-1" selected="selected">请选择分类</option>
               	 <c:forEach var="item" varStatus="status" items="${pcL3List}">
                   	 <option value="${item.id }" <c:if test="${item.id == phProductVo.productClassifyId}"> selected="selected"</c:if>>${item.classifyName}</option>
                    </c:forEach>
                </select>
            </div>
        </div>
        </div>
        <!-- 属性值 -->
        <div id="allProperty">
        	<c:forEach var="property" varStatus="status" items="${phProductVo.phProductPropertyVoList}">
        	<div class="form-group col-sm-12 ppvDiv" ide="${property.id}" classifyId=${property.classifyId }><!--  id="group" -->
			<label for="" class="col-sm-1 control-label">${property.propertyName }</label>
       		<c:forEach var="propertyVal" varStatus="status" items="${phProductVo.phProductPropertyValVoList}">
       			<c:if test="${propertyVal.propertyId == property.id}"> 
		            <div class="col-sm-1">
		                <input type="text" class="form-control pvcontent p_${property.id}" ide="${property.id}" name="content" value="${propertyVal.content }"
		                       placeholder="" /><span onclick="deleteDiv(this)" class="fa fa-minus"></span>
		            </div>
		            </c:if>
            </c:forEach>
            <!-- id="addInput" --><span class="col-sm-1 addppvInput" ide="${property.id}" ><i class="fa fa-plus fa-2" aria-hidden="true"></i></span>
            </div>
           </c:forEach>
          </div> 
            <div class="form-group">
	            <div class="col-sm-12" style="text-align: center;">
	                <button type="button" id="save" class="btn btn-primary btn-10">保存</button>
	                <button type="button" onclick="javascript:window.location.href='${ctx}/api/product/listPage'" class="btn btn-primary btn-10">返回</button>
	            </div>
	        </div>
        
    </div>
    <input type="hidden" name="id" id="id" value="${phProductVo.id}"/>
    <input type="hidden" name="productClassifyId" id="productClassifyId" value="${phProductVo.productClassifyId}"/>
    <div id="descriptionHidden" style="display: none;">${phProductVo.description}</div><!-- 存富文本值 -->
    <input type="hidden" id="levleHidden" value=""/>
    <input type="hidden" id="productPropertyValJSON"  name="productPropertyValJSON" value=""/>
    <input type="hidden" id="imageJSON"  name="imageJSON" value=""/>
    <div id="imgHidden">
   
    </div>
    </form>
</div>
<script charset="utf-8" src="${ctx}/static/plugins/kindeditor-4.1.7/kindeditor.js"></script>
<script src="${ctx}/static/plugins/jQuery/jQuery-2.1.4.min.js"></script>
<script src="${ctx}/static/bootstrap/js/bootstrap.min.js"></script>
<script src="${ctx}/static/plugins/layer/layer.js"></script>
<script src="${ctx}/static/plugins/validationEngine/jquery.validationEngine-zh_CN.js"></script>
<script src="${ctx}/static/plugins/validationEngine/jquery.validationEngine.js"></script>
<script src="${ctx}/static/plugins/ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="${ctx}/static/plugins/zyupload/zyupload-1.0.0.js"></script>
<script charset="utf-8" src="${ctx}/static/plugins/kindeditor-4.1.7/lang/zh_CN.js"></script>
<script type="text/javascript">
var editor;
/*添加删除属性表单*/
$(function () {
	//富文本编辑器初始化
	 KindEditor.ready(function(K) {
	     editor= K.create('#description',{
	    	   	    uploadJson : '${ctx}/uploadProductImage?module=editor',
	    	   	    resizeModel:1,
	    	 		allowFileManager : false,
	    	 		allowFlashUpload:false,
	    	 		allowMediaUpload:false,
	    	 		formatUploadUrl:false,  
	    	 		items:[
	    	 		        'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'cut', 'copy', 'paste',
	    	 		        'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
	    	 		        'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
	    	 		        'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
	    	 		        'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
	    	 		        'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image',
	    	 		        'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
	    	 		        'anchor', 'link', 'unlink', '|', 'about'
	    	 		],
	     	});
				
	});
	$("#updateForm").validationEngine({ 
		promptPosition: "topRight", 
		validationEventTriggers:"keyup blur", 
		success :  false,
		failure : function() { callFailFunction()  }
		});
    $(".addppvInput").click(function (e) {
    	var group = $(e.target).parent().parent();
    	var ide =$(e.target).parent().attr("ide");
        var i= group.find("div[ref='add']").length;
        $(this).before('<div  ref="add" class="col-sm-1"><input type="text" ide="' + ide + '" name="content" class="form-control pvcontent p_' + ide + '"' + 
            ' placeholder=""><span onclick="deleteDiv(this)" class="fa fa-minus"></span></div>');
	});
	
    $("#save").click(function() {
    	//基础验证
    	var flag = $("#updateForm").validationEngine("validate");
    	if(!flag){
     		return false;
    	} 
    	//获取富文本的值	
     	var content= editor.html();
     	$("#descriptionHidden").html(content);
    	//获取表单数据
    	var obj = $("#updateForm").serialize();
    	//组装属性值
    	var productPropertyValJSON = [];
    	$(".pvcontent").each(function(){
    		if(null != $(this).val() && "" != $.trim($(this).val()) ){
    			var obj = new Object();
    			obj.propertyId = $(this).attr("ide");
    			obj.content = $.trim($(this).val());
    			productPropertyValJSON.push(obj);
    		}
    	  });
    	$("#productPropertyValJSON").val(JSON.stringify(productPropertyValJSON));
    	
    	var imageJSON = [];
    	$(".hImag").each(function(i, n){
    		if(null != $(this).val() && "" != $.trim($(this).val()) ){
    			var obj = new Object();
    			obj.sort = i;
    			obj.url = $.trim($(this).val());
    			imageJSON.push(obj);
    		}
    	  });
    	if(imageJSON.length>5){
    		alert("上传图片不能超过5张");
    		return false;
    	}
    	$("#imageJSON").val(JSON.stringify(imageJSON));
    	//提交数据
    	$.ajax({
    		async       : false,
    		type 		: "POST",
    	    url		    : "${ctx}/api/product/updateProduct?content=" + content,
    		data 		: $("#updateForm").serialize(),
    		success 	: function(d) {
    			if(d.code == 200){
    				layer.msg('修改商品成功',{icon: 1, time: 2000},
    						function(index){
		            	window.location.href="${ctx}/api/product/listPage";
		            });
    			} else {
    				layer.msg('修改失败',{icon: 2});
    			}
    		}
    	});
    });
    
    
    // 初始化插件
	$("#zyupload").zyUpload({
		width            :   "1000px",                 // 宽度
		height           :   "500px",                 // 宽度
		itemWidth        :   "140px",                 // 文件项的宽度
		itemHeight       :   "115px",                 // 文件项的高度
		url              :   "${ctx}/api/attachment/uploadProductImage?module=product", 
		fileType         :   ["jpg","png","gif","bmp","jpeg"],// 上传文件的类型
		fileSize         :    5242880,               // 上传文件的大小
		multiple         :   true,                    // 是否可以多个文件上传
		dragDrop         :	 false,                    // 是否可以拖动上传文件
		tailor           :   false,                    // 是否可以裁剪图片
		del              :   true,                    // 是否可以删除文件
		finishDel        :   false,  				  // 是否在上传文件完成后删除预览
		/* 外部获得的回调接口 */
		onSelect: function(selectFiles, allFiles){    // 选择文件的回调方法  selectFile:当前选中的文件  allFiles:还没上传的全部文件
		},
		onDelete: function(file, files){              // 删除一个文件的回调方法 file:当前删除的文件  files:删除之后的文件
			$("#img" + file.index).remove();
		},
		onSuccess: function(file, response){          // 文件上传成功的回调方法
			var rs = JSON.parse(response);
			$("#imgHidden").append('<input type="hidden" name="image" id="img'+ file.index +'" class="hImag" value="'+ rs.data +'"/>');
		},
		onFailure: function(file, response){          // 文件上传失败的回调方法
		},
		onComplete: function(response){           	  // 上传完成的回调方法
		}
	});
    
});

function deleteDiv(sp){
     $(sp).parent().remove();
}
        
function getClass(id,level){
	$("#levleHidden").val("");
	$("#levleHidden").val(level);
	if(id!=""){
	$.ajax({url:'${ctx}/api/productClassify/selectClass?id='+id,dataType:"json",type:"post",success:savecallbackOne,error:function(data){
				layer.alert("与服务器连接中断");
 }});
	}
}
function savecallbackOne(data){
	var levle=$("#levleHidden").val();
	if(levle=="second"){
		$("#three").find("option").remove();
		$("#three").prepend("<option value=''>请选择分类</option>");
	}
	$("#"+levle).find("option").remove();
	$("#"+levle).prepend("<option value=''>请选择分类</option>");
	for(var i=0; i<data.data.length;i++){
        $("#"+levle).append("<option value='"+data.data[i].id+"'>"+data.data[i].classifyName+"</option>");
    }
	$("#allProperty").html("");
}


function gerProperties(){
	var fid=$("#first").val();
	var sid=$("#second").val();
	var tid=$("#three").val();
	if(fid==""||sid==""||tid==""){
		layer.alert("请选择分类");
		return false;
	}
	$.ajax({url:'${ctx}/api/product/getClassifiesForThreeId?fid='+fid+'&sid='+sid+'&tid='+tid,dataType:"json",type:"get",success:savecallback,error:function(data){
				layer.alert("与服务器连接中断");
	}});
}

//成功回调方法
function savecallback(data){
	$("#allProperty").html("");
	//$(".ppvDiv").remove();
	var html="";
	for(var i=0; i<data.data.length;i++){
		html+="<div class='form-group col-sm-12 ppvDiv'  ide="+data.data[i].id+" classifyId="+data.data[i].classifyId+">";
		html+="<label for='' class='col-sm-1 control-label'>"+data.data[i].propertyName +"</label>";
		html+=" <div class='col-sm-1'>";
		html+="<input type='text' class='form-control  pvcontent p_"+data.data[i].id+"'  ide="+data.data[i].id+" name='content'  value='' placeholder='' /><span onclick='deleteDiv(this)' class='fa fa-minus'></span>";
		html+="</div>";
		html+="<span class='col-sm-1 addppvInput' ide="+data.data[i].id+" ><i class='fa fa-plus fa-2' aria-hidden='true'></i></span>";
		html+="</div>";
	}
	$("#allProperty").append(html);
	
	$(".addppvInput").click(function (e) {
    	var group = $(e.target).parent().parent();
    	var ide =$(e.target).parent().attr("ide");
        var i= group.find("div[ref='add']").length;
        $(this).before('<div  ref="add" class="col-sm-1"><input type="text" ide="' + ide + '" name="content" class="form-control pvcontent p_' + ide + '"' + 
            ' placeholder=""><span onclick="deleteDiv(this)" class="fa fa-minus"></span></div>');
	});
}
//设置进货价
function setPurchasePrice(){
	var retailPrice = $("#retailPrice").val();
	var purchasePrice = (retailPrice * 0.61).toFixed(2);
	$("#purchasePrice").val(purchasePrice);
}
</script>
</body>
</html>